<!DOCTYPE HTML>
<%
    def paymentService = grailsApplication.mainContext.getBean("paymentService");
%>
<html lang="en">
	<head>
		<meta name="layout" content="main">
		<g:set var="entityName" value="${message(code: 'collectReward.label', default: 'Return My Item')}" />
		<title>${entityName}</title>
		<r:require modules="jquery-ui, stripe"/>
	</head>

	<body>
		<div id="width960">
			<div id="notag-box" class="formBox">
				<g:if test="${flash.message}">
					<div class="message" role="status">${flash.message}</div>
				</g:if>
				<g:hasErrors bean="${cmd}">
					<ul class="errors" role="alert">
						<g:eachError bean="${cmd}" var="error">
						<li <g:if test="${error in org.springframework.validation.FieldError}">data-field-id="${error.field}"</g:if>><g:message error="${error}"/></li>
						</g:eachError>
					</ul>
				</g:hasErrors>
				
				<div class="wizardStepDisplay" style="padding: 0 90px;">
					<div class="reward_sprite ${cmd.wizardStep}"></div>
				</div>
			
				<div class="row">
					<div class="col c1">&nbsp;</div>
					<div class="col c10">		
						<g:form action="rewardNext" name="payment-form">
							<g:hiddenField name="eventId" value="${cmd.eventId}"/>
							<g:hiddenField name="wizardStep" value="${cmd.wizardStep}"/>
							<g:hiddenField name="shipDefault" value="${cmd.shipDefault}"/>

							<fieldset class="embedded">
								<g:if test="${cmd.wizardStep =='reward' }">
									<legend>Reward Finder</legend>
									<div class="instructions">
										<p><g:message code="collectReward.label.rewardAmount.instructions" default="Select Reward:" /></p>
									</div>
									<div class="fieldcontain">
										<label for="slider"><g:message code="collectReward.rewardSlider" default="Select Reward:" /></label>
										<div id="slider" style="display: inline-block; width: 70%;"></div>
									</div>
									<div class="fieldcontain ${hasErrors(bean: cmd, field: 'rewardAmount', 'error')} required">
										<label for="rewardAmount"><g:message code="collectReward.label.rewardAmount" default="Reward Amount:" /></label>
										<span class="required-indicator">*</span>
										<g:textField name="rewardAmount" class="formTextInput" value="${cmd?.rewardAmount }"/>
									</div>
								</g:if>
								<g:if test="${cmd.wizardStep =='shipping' }">
									<legend>Shipping Option</legend>
									<g:if test="${cmd.event.canContactDirect}">
										<div class="fieldcontain required">
											<label for="ship"><g:message code="collectReward.label.ship" default="Ship Item:" /></label>
											<g:checkBox name="ship" value="${cmd.ship ?: cmd.shipDefault }"/>
											<div class="instructions"><p><g:message code="collectReward.label.shipping.instructions" default="Shipping Instructions" /></p></div>
										</div>
									</g:if>
									<g:else>
										<g:hiddenField name="ship" value="true"/>
									</g:else>
									<div id="shippingInfo">
										<div class="fieldcontain ${hasErrors(bean: cmd, field: 'contact.name', 'error')} required">
											<label for="contactname"><g:message code="found.label.contact.name" default="Name:" /></label>
											<span class="required-indicator">*</span>
											<g:textField hint="Enter Name" id="contactname" name="contact.name" class="formTextInput" value="${cmd.contact?.name }"/>
										</div>
										<fieldset class="nested">
											<legend>Shipping Options</legend>
											<g:hiddenField name="carrier" value="${paymentService.getShippingCarriers()[0] }"/>
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'packageType', 'error')} required">
												<label for="packageType"><g:message code="collectReward.label.shipping.packageType" default="Parcel Type:" /></label>
												<select id="packageType" name='packageType' value="${cmd.packageType}">
													<option value="">Select Package Type...</option>
													<g:each in='${paymentService.getShippingContainerTypes()}'>
														<option value='${it.packageType }' dimensions='${"Package Dimensions: " + it.dimensions.height + " X " + it.dimensions.width + " X " + it.dimensions.depth + " Inches"}' selected='${it.packageType ==  cmd.packageType}'>${it.packageType }</option>
													</g:each>
												</select>
												<div id="dimensions" class="instructions"><p></p></div>
											</div>
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'speed', 'error')} required">
												<label for="speed"><g:message code="collectReward.label.shipping.speed" default="Return Speed:" /></label>
												<g:select name='speed' value="${cmd.speed?.key}"
												    noSelection="${['':'Select Return Speed...']}"
												    from='${paymentService.getShippingSpeeds()}' optionKey='key' />
											</div>
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'estimatedWeight', 'error')} required">
												<label for="estimatedWeight"><g:message code="collectReward.label.shipping.estimatedWeight" default="Estimated Weight:" /></label>
												<g:textField name='estimatedWeight' value="${cmd.estimatedWeight}" />
											</div>
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'insuredAmount', 'error')} required">
												<label for="insuredAmount"><g:message code="collectReward.label.shipping.insuredAmount" default="Insured Value:" /></label>
												<g:textField name='insuredAmount' value="${cmd.insuredAmount}" />
											</div>
											<div id="shippingCharge" class="instructions"><p></p></div>
										</fieldset>
										<br/>
										<fieldset class="nested">
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'phone', 'error')} required">
												<label for="contactphone"><g:message code="found.label.contact.phone" default="Phone:" /></label>
												<span class="required-indicator">*</span>
												<g:textField hint="Enter Phone" name="phone" name="phone" class="formTextInput" value="${cmd.phone}"/><br/>
											</div>
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'useSms', 'error')}">
												<label for="useSms"><g:message code="found.label.contact.sms" default="SMS:" /></label>
												<g:checkBox name="useSms" value="${cmd.useSms}"/><br/>
											</div>
										</fieldset>
										<div class="fieldcontain ${hasErrors(bean: cmd, field: 'contactemail', 'error')} required">
											<label for="contactemail"><g:message code="found.label.contact.email" default="E-Mail:" /></label>
											<span class="required-indicator">*</span>
											<input type="text" hint="Enter e-mail" id="contactemail" name="contact.email" class="formTextInput" value="${cmd.contact?.email}"/>
										</div>
										<div class="fieldcontain ${hasErrors(bean: cmd, field: 'contactskype', 'error')}">
											<label for="contactSkype"><g:message code="found.label.contact.skype" default="Skype:" /></label>
											<input type="text" hint="Enter skype ID" id="contactskype" name="contact.skypeId" class="formTextInput" value="${cmd.contact?.skypeId}"/>
										</div>
										<fieldset class="nested">
											<legend>Mailing Location for Return Container</legend>
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'mailing.address1', 'error')}">
												<label for="mailing.address1">
													<g:message code="appUser.mailing.address1.label" default="Address1" />
													<span class="required-indicator">*</span>
												</label>
												<g:textField name="mailing.address1" required="" value="${cmd.mailing?.address1}"/>
											</div>
											
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'mailing.address2', 'error')} ">
												<label for="mailing.address2">
													<g:message code="appUser.mailing.address2.label" default="Address2" />
													
												</label>
												<g:textField name="mailing.address2" value="${cmd.mailing?.address2}"/>
											</div>
											
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'mailing.country', 'error')} required">
												<label for="mailing.country">
													<g:message code="appUser.mailing.country.label" default="Country" />
													<span class="required-indicator">*</span>
												</label>
												<g:select name="mailing.country" from="${['US', 'CA']}"
			         								 valueMessagePrefix="mailing.country" />
											</div>
											
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'mailing.zipCode', 'error')} required">
												<span class="required-indicator"style="margin-left:25px;">Begin typing a Zip code and select your City and State:</span><br/>
												<label for="mailing.zipCode">
													<g:message code="appUser.mailing.zipCode.label" default="Zip Code" />
													<span class="required-indicator">*</span>
												</label>
												<g:textField name="mailing.zipCode" pattern="${cmd.mailing.constraints.zipCode.matches}" required="" value="${cmd.mailing?.zipCode}"/>
											</div>
											
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'mailing.city', 'error')} required">
												<label for="mailing.city">
													<g:message code="appUser.mailing.city.label" default="City" />
													<span class="required-indicator">*</span>
												</label>
												<g:textField name="mailing.city" required="" value="${cmd.mailing?.city}"/>
											</div>
											
											<div class="fieldcontain ${hasErrors(bean: cmd, field: 'mailing.state', 'error')} required">
												<label for="mailing.state">
													<g:message code="appUser.mailing.state.label" default="State" />
													<span class="required-indicator">*</span>
												</label>
												<g:textField name="mailing.state" required="" value="${cmd.mailing?.state}"/>
											</div>
										</fieldset>									
									</div>
								</g:if>
								<g:if test="${cmd.wizardStep =='payment' }">
									<legend>Payment</legend>
									<g:hiddenField name='packageType' value="${cmd.packageType}"/>
									<g:hiddenField name='speed' value="${cmd.speed.key}"/>
									<g:hiddenField name='estimatedWeight' value="${cmd.estimatedWeight}"/>
									<g:hiddenField name='insuredAmount' value="${cmd.insuredAmount}"/>
									<div class="errors payment-errors display-none"></div>
									<div class="instructions">
										<p>Charge summary:</p>
										<p><ul>
											<li>Reward Amount: ${cmd.event.rewardAmount}</li>
											<li>Shipping Amount: ${cmd.event.shippingAmount}</li>
											<li>Handling Amount: ${cmd.event.handlingAmount}</li>
										</ul></p>
										<g:hiddenField name="chargeamount" value="${cmd.chargeamount }"/>
									</div>
									<div class="fieldcontain required">
										<label for="chargeamount">
											<g:message code="found.chargeamount.label" default="Amount" />
											<span class="required-indicator">*</span>
										</label>
										<g:textField name="chargeAmount1" value="${cmd.chargeamount}" disabled="true"/>
									</div>
									<stripe:creditCardInputs cssClass="fieldcontain"/>
								</g:if>
								<g:if test="${cmd.wizardStep =='complete' }">
									<legend>Complete</legend>
									<div class="instructions">
										<p>Your ${cmd.event.item.name} is on it's way home!  You will be receive tracking numbers when they are assigned so you can follow it's journey home.</p>
										<g:if test="${!cmd.event.processShipping}">
											<p>You opted to contact the Finder of ${cmd.event.item.name} directly.  The contact information is shown below and will be e-mailed to the address on file:</p>
											<p>${cmd.event.finderContact.name}</p>
											<p>${cmd.event.finderContact.cellPhone}</p>
											<p>${cmd.event.finderContact.phone2}</p>
											<p>${cmd.event.finderContact.email}</p>
											<p>${cmd.event.finderContact.skypeId}</p>
										</g:if>
									</div>
								</g:if>
								<div class="buttons">
									<g:if test="${ cmd.wizardStep != 'reward' && cmd.wizardStep != 'complete' }">
										<g:submitButton class="basic-ok-button submitButton" name="previous" value="Previous" action="previous"/>
									</g:if>
									<g:submitButton class="basic-ok-button submitButton" name="Next" value="${ cmd.wizardStep == 'complete' ? 'Finish' : 'Next' }"/>
								</div>
							</fieldset>
									
						</g:form>
					</div>
				</div>
			</div>		
		</div>
		
		<r:script disposition="head">
		<!--
	    Stripe.setPublishableKey('${grailsApplication.config.grails.plugins.stripe.publishableKey}');

		function stripeResponseHandler(status, response) {
		    if (response.error) {
		        // show the errors on the form
		        $(".payment-errors").text(response.error.message);
		        $(".submitButton").removeAttr("disabled");
		    } else {
		        var form$ = $("form");
		        // token contains id, last4, and card type
		        var token = response['id'];
		        // insert the token into the form so it gets submitted to the server
		        form$.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
		        // and submit
		        form$.get(0).submit();
		    }
		}

		$(document).ready(function(){
		    
		    var packageType, speed, weight = $('#estimatedWeight').val(), insured = $('#insuredAmount').val();
		    
		    $('#packageType').change(function(){
		    	var dimensionDesc = $('option:selected', this).attr('dimensions');
		    	$('#dimensions p').text(dimensionDesc);
		    	packageType = $(this).val();
		    	callFedexWS();
		    })
			   
		    $('#speed').change(function(){
		    	speed = $(this).val();
		    	callFedexWS();
			});
			   
		    $('#estimatedWeight').blur(function(){
		    	speed = $(this).val();
		    	callFedexWS();
			});
			   
		    $('#insuredAmount').blur(function(){
		    	insured = $(this).val();
		    	callFedexWS();
			});

		    $( "#slider" ).slider({
		        value:50,
		        min: 25,
		        max: 500,
		        step: 5,
		        slide: function( event, ui ) {
		            $( "#rewardAmount" ).val( "$" + ui.value + ".00" );
		        }
		    });
		    $( "#rewardAmount" ).val( "$" + $( "#slider" ).slider( "value" ) + ".00");

		    $('form').on('click', '#ship', function(){
				if ($(this).is(':checked')) {
					$('#shippingInfo').show();
				}
				else {
					$('#shippingInfo').hide();
				}
			});

			var submitButton = undefined;
			$('form').find(':submit').live('mouseup keyup',function(){
			    submitButton  = $(this);
			});
		    $("form").submit(function(event) {
		        // disable the submit button to prevent repeated clicks
		        $('.submitButton').attr("disabled", "disabled");

			    if ($('#wizardStep').val() == 'payment' && submitButton.attr('name') == 'Next') {
			        Stripe.createToken({
			            number: $('.card-number').val(),
			            cvc: $('.card-cvc').val(),
			            exp_month: $('.card-expiry-month').val(),
			            exp_year: $('.card-expiry-year').val()
			        }, stripeResponseHandler);
			        $('#chargeamount').removeAttr('disabled');
			        $('.display-none').show()

			        // prevent the form from submitting with the default action
			        return false;
				}
				
				$('<input>').attr({
				    type: 'hidden',
				    id: 'buttonid',
				    name: submitButton.attr('name'),
				    value: submitButton.attr('value')  
				}).appendTo('#payment-form');
				
				return true;
		    });
		    
		    function callFedexWS() {
		    	if (!packageType || !speed || !weight)
		    		return;
		    		
		    	var eventId = $('#eventId').val();
		    	var url = "${createLink(controller:'found', action:'searchShippingRateJson', params:[eventId:'', packageType:'', speed:'', weight:'', insuredAmount:''])}";
		    	url = url.replace('eventId=','eventId='+eventId)
		    			.replace('packageType=','packageType='+packageType)
		    			.replace('speed=','speed='+speed)
		    			.replace('weight=','weight='+weight)
		    			.replace('insuredAmount=','insuredAmount='+insured);
                $.ajax({
                    url: url,
                    success: function( data ) {
                    	var total = 0;
                        $.each(data, function() {
						    total += this.amount;
						});
						$('#shippingCharge p').text('Estimated Shipping Charge: ' + total + ' ' + data[0].currency);
                    }
                });
  
		    }
		});
		-->
		</r:script>
	</body>

</html>
